//
//  MyAdvisoryOrderController.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/3/19.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit

class MyAdvisoryOrderController: BaseViewController {
    
    private var status: OrderStatus
    
    init(with status: OrderStatus) {
        self.status = status
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private var viewModel: MyAdvisoryOrderViewModel? {
        didSet {
            guard let vm = viewModel else { return }
            tableview.isHidden = vm.showEmptyView
            emptyView.isHidden = !vm.showEmptyView
            
            emptyView.refreshClosure = { [weak self] in
                self?.tableview.isHidden = false
                self?.emptyView.isHidden = true
                self?.tableview.mj_header?.beginRefreshing()
            }
            
            tableview.reloadData()
        }
    }

    @IBOutlet private weak var tableview: UITableView! {
        didSet {
            tableview.backgroundColor = .background
            tableview.tableFooterView = UIView()
            tableview.contentInset = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 0)
            tableview.register(MyAdvisoryCommentOrderCell.nibForCell(),
                               forCellReuseIdentifier: MyAdvisoryCommentOrderCell.reuseIdentifier())
            tableview.register(MyAdvisoryOrderCell.nibForCell(),
                               forCellReuseIdentifier: MyAdvisoryOrderCell.reuseIdentifier())
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        emptyView.configure(with: UIImage(named: "empty_order"), title: "您还没有图文问诊订单哦~")
        setupRefresh()
    }
}

extension MyAdvisoryOrderController {
    private func setupRefresh() {
        tableview.mj_header = refreshHeader(action: #selector(loadData))
        tableview.mj_header?.beginRefreshing()
    }
    
    private func endRefresh() {
        tableview.mj_header?.endRefreshing()
    }
    
    @objc private func loadData() {
        refreshData(isHeader: true)
    }
    
    private func refreshData(isHeader: Bool = false) {
        MyOrderViewModel.getMyAdvisoryOrder(userId: UserDefaults.userId,
                                            status: status.rawValue,
                                            success: { models in
            if isHeader { self.endRefresh() }
            self.viewModel = MyAdvisoryOrderViewModel(models: models)
        }) { errorMsg in
            if isHeader { self.endRefresh() }
            HUDTool.showError(message: errorMsg)
        }
    }
}

// MARK: - DataSource && Delegate
extension MyAdvisoryOrderController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel?.numberOfRows ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let vm = viewModel?.viewModel(for: indexPath) else { return UITableViewCell() }
        
        switch vm.status {
        case .comment:
            let cell = tableView.dequeueReusableCell(withIdentifier: MyAdvisoryCommentOrderCell.reuseIdentifier(),
                                                     for: indexPath) as! MyAdvisoryCommentOrderCell
            cell.configure(with: vm)
            return cell
        default:
            let cell = tableView.dequeueReusableCell(withIdentifier: MyAdvisoryOrderCell.reuseIdentifier(),
                                                     for: indexPath) as! MyAdvisoryOrderCell
            cell.delegate = self
            cell.configure(with: vm)
            return cell
        }
        
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        guard let vm = viewModel?.viewModel(for: indexPath) else { return 0 }
        return vm.cellHeight
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        guard let vm = viewModel?.viewModel(for: indexPath) else { return }
        
        switch vm.status {
        case .waitPay:
            pushOrderDetailVc(vm)
        case .processing, .notStart:
            let chatVc = ChatViewController(with: vm.diagnoseId)
            chatVc.businessType = vm.model.businessType
            navigationController?.pushViewController(chatVc, animated: true)
        case .comment, .finish:
            let vc = MyAdvisoryOrderFinishController(with: vm.diagnoseId)
            vc.closure = { [weak self] in
                self?.setupRefresh()
            }
            navigationController?.pushViewController(vc, animated: true)
        default: break
        }
    }
}

extension MyAdvisoryOrderController: MyAdvisoryOrderCellDelegate {
    func orderCell(didTappedDelete cell: MyAdvisoryOrderCell) {
        guard let indexPath = tableview.indexPath(for: cell),
            let vm = viewModel?.viewModel(for: indexPath) else { return }
        
        AlertTool.showAlert(self, message: "确定要取消订单吗？", type: .double, sureHandler: { _ in
            self.cancelOrder(orderId: vm.orderId, indexPath: indexPath)
        })
    }
    
    private func cancelOrder(orderId: String, indexPath: IndexPath) {
        MyOrderViewModel.cancelOrder(orderId: orderId) { (errorMsg, code) in
            switch code {
            case .failure:
                HUDTool.showError(message: errorMsg)
            case .success:
                HUDTool.show(message: "删除订单成功")
                self.refreshData()
            }
        }
    }
    
    func orderCell(didTappedRefound cell: MyAdvisoryOrderCell) {
        guard let indexPath = tableview.indexPath(for: cell),
            let vm = viewModel?.viewModel(for: indexPath) else { return }
        
        HUDTool.showActivity()
        MyOrderViewModel.orderRefound(orderNumber: vm.orderNumber) { (success, errorMsg) in
            HUDTool.hideActivity()
            if !success {
                HUDTool.showError(message: errorMsg)
            } else {
                HUDTool.show(message: "退款成功")
                self.refreshData()
            }
        }
    }
    
    private func pushOrderDetailVc(_ vm: MyAdvisoryOrderRowViewModel) {
        let orderDetailVc = MyAdvisoryOrderDetailController(with: vm)
        navigationController?.pushViewController(orderDetailVc, animated: true)
        orderDetailVc.handlerClosure = { [weak self] in
            self?.refreshData()
        }
    }
}
